#include <tinx/types.h>

#define SEPARATOR1 '/'                                       // 目录分隔符 1
#define SEPARATOR2 '\\'                                      // 目录分隔符 2
#define IS_SEPARATOR(c) (c == SEPARATOR1 || c == SEPARATOR2) // 字符是否位目录分隔符

size_t strlen(char *str)
{
    char *ptr = (char *)str;
    while (*ptr != '\0')
        ptr++;
    return ptr - str;
}

size_t strnlen(char *str, int maxlen)
{
    char *ptr = (char *)str;
    while (*ptr != '\0' && maxlen--)
        ptr++;
    return ptr - str;
}

size_t strnamelen(char *name)
{
    char *ptr = (char *)name;
    while (*ptr != '\0' && *ptr != '/')
        ptr++;
    return ptr - name;
}

int strcpy(char *dest, char *src)
{
    int nr = 0;
    while (*src != '\0')
    {
        nr++;
        *dest++ = *src++;
    }
    *dest = '\0';
    return nr;
}

void strcast(char *dest, char *src)
{
    int i = strlen(dest);
    strcpy(&dest[i], src);
}

int strcmp(char *cs, char *ct)
{
    unsigned char c1, c2;

    while (1)
    {
        c1 = *cs++;
        c2 = *ct++;
        if (c1 != c2)
            return c1 < c2 ? -1 : 1;
        if (!c1)
            break;
    }
    return EOK;
}

void memcpy(void *dest, void *src, int count)
{
    u8 *ptr = dest;
    while (count--)
    {
        *ptr++ = *((u8 *)src++);
    }
}

char *strncpy(char *dest, char *src, size_t count)
{
    char *ptr = dest;
    size_t nr = 0;
    for (; nr < count; nr++)
    {
        *ptr++ = *src;
        if (*src++ == EOS)
            return dest;
    }
    dest[count - 1] = EOS;
    return dest;
}

// 获取第一个分隔符
char *strsep(char *str)
{
    char *ptr = (char *)str;
    while (true)
    {
        if (IS_SEPARATOR(*ptr))
        {
            return ptr;
        }
        if (*ptr++ == EOS)
        {
            return NULL;
        }
    }
}

// 获取最后一个分隔符
char *strrsep(char *str)
{
    char *last = NULL;
    char *ptr = (char *)str;
    while (true)
    {
        if (IS_SEPARATOR(*ptr))
        {
            last = ptr;
        }
        if (*ptr++ == EOS)
        {
            return last;
        }
    }
}

char *strrname(char *str)
{
    char *last = str;
    char *ptr = (char *)str;
    while (true)
    {
        if (IS_SEPARATOR(*ptr) && *(ptr + 1))
        {
            last = ptr + 1;
        }
        if (*ptr++ == EOS)
        {
            return last;
        }
    }
}

void memset(void *dest, u8 data, int count)
{
    char *ptr = dest;
    while (count--)
        *ptr++ = data;
}

int memcmp(void *_cs, void *_ct, int count)
{
    char *cs = (char *)_cs;
    char *ct = (char *)_ct;
    size_t c1, c2;

    for (size_t i = 0; i < count; i++)
    {
        c1 = *cs++;
        c2 = *ct++;
        if (c1 != c2)
            return c1 < c2 ? -1 : 1;
    }
    return 0;
}